/**
 * 用户状态管理模块
 * 管理用户信息、登录状态、权限等
 */

import { defineStore } from 'pinia/dist/pinia.mjs'
import { userApi } from '@/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    // 登录token
    token: '',
    // 是否已登录
    isLoggedIn: false,
    // 用户设置
    settings: {
      theme: 'light', // 主题：light/dark
      language: 'zh-CN', // 语言
      notifications: {
        habits: true,
        finance: true,
        todos: true,
        system: true
      },
      privacy: {
        dataSync: true,
        analytics: false
      }
    },
    // 加载状态
    loading: {
      login: false,
      userInfo: false,
      settings: false
    }
  }),

  getters: {
    // 获取用户头像
    avatar: (state) => {
      return state.userInfo?.avatar || '/static/images/default-avatar.png'
    },
    
    // 获取用户昵称
    nickname: (state) => {
      return state.userInfo?.nickname || state.userInfo?.username || '未设置昵称'
    },
    
    // 获取用户ID
    userId: (state) => {
      return state.userInfo?.id
    },
    
    // 是否是VIP用户
    isVip: (state) => {
      return state.userInfo?.vip || false
    },
    
    // 获取用户权限
    permissions: (state) => {
      return state.userInfo?.permissions || []
    }
  },

  actions: {
    /**
     * 用户登录
     * @param {Object} loginData 登录数据
     */
    async login(loginData) {
      this.loading.login = true
      try {
        const response = await userApi.login(loginData)
        const { token, userInfo } = response.data
        
        // 保存token和用户信息
        this.token = token
        this.userInfo = userInfo
        this.isLoggedIn = true
        
        // 保存到本地存储
        uni.setStorageSync('token', token)
        uni.setStorageSync('userInfo', userInfo)
        
        return response
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      } finally {
        this.loading.login = false
      }
    },

    /**
     * 用户注册
     * @param {Object} registerData 注册数据
     */
    async register(registerData) {
      try {
        const response = await userApi.register(registerData)
        return response
      } catch (error) {
        console.error('注册失败:', error)
        throw error
      }
    },

    /**
     * 获取用户信息
     */
    async getUserInfo() {
      if (!this.token) {
        throw new Error('未登录')
      }
      
      this.loading.userInfo = true
      try {
        const response = await userApi.getUserInfo()
        this.userInfo = response.data
        
        // 更新本地存储
        uni.setStorageSync('userInfo', this.userInfo)
        
        return response
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果token无效，清除登录状态
        if (error.code === 401) {
          this.logout()
        }
        throw error
      } finally {
        this.loading.userInfo = false
      }
    },

    /**
     * 更新用户信息
     * @param {Object} updateData 更新数据
     */
    async updateUserInfo(updateData) {
      try {
        const response = await userApi.updateUserInfo(updateData)
        
        // 更新本地用户信息
        this.userInfo = { ...this.userInfo, ...response.data }
        uni.setStorageSync('userInfo', this.userInfo)
        
        return response
      } catch (error) {
        console.error('更新用户信息失败:', error)
        throw error
      }
    },

    /**
     * 修改密码
     * @param {Object} passwordData 密码数据
     */
    async changePassword(passwordData) {
      try {
        const response = await userApi.changePassword(passwordData)
        return response
      } catch (error) {
        console.error('修改密码失败:', error)
        throw error
      }
    },

    /**
     * 用户登出
     */
    async logout() {
      try {
        // 调用登出接口
        if (this.token) {
          await userApi.logout()
        }
      } catch (error) {
        console.error('登出接口调用失败:', error)
      } finally {
        // 清除本地状态
        this.token = ''
        this.userInfo = null
        this.isLoggedIn = false
        
        // 清除本地存储
        uni.removeStorageSync('token')
        uni.removeStorageSync('userInfo')
        
        // 跳转到登录页
        uni.reLaunch({
          url: '/pages/login/index'
        })
      }
    },

    /**
     * 刷新token
     */
    async refreshToken() {
      try {
        const response = await userApi.refreshToken()
        const { token } = response.data
        
        this.token = token
        uni.setStorageSync('token', token)
        
        return response
      } catch (error) {
        console.error('刷新token失败:', error)
        // token刷新失败，重新登录
        this.logout()
        throw error
      }
    },

    /**
     * 获取用户设置
     */
    async getUserSettings() {
      this.loading.settings = true
      try {
        const response = await userApi.getUserSettings()
        this.settings = { ...this.settings, ...response.data }
        return response
      } catch (error) {
        console.error('获取用户设置失败:', error)
        throw error
      } finally {
        this.loading.settings = false
      }
    },

    /**
     * 更新用户设置
     * @param {Object} settingsData 设置数据
     */
    async updateUserSettings(settingsData) {
      try {
        const response = await userApi.updateUserSettings(settingsData)
        this.settings = { ...this.settings, ...settingsData }
        return response
      } catch (error) {
        console.error('更新用户设置失败:', error)
        throw error
      }
    },

    /**
     * 初始化用户状态
     * 从本地存储恢复登录状态
     */
    initUserState() {
      const token = uni.getStorageSync('token')
      const userInfo = uni.getStorageSync('userInfo')
      
      if (token && userInfo) {
        this.token = token
        this.userInfo = userInfo
        this.isLoggedIn = true
        
        // 验证token有效性
        this.getUserInfo().catch(() => {
          // token无效，清除登录状态
          this.logout()
        })
      }
    },

    /**
     * 检查登录状态
     */
    checkLoginStatus() {
      if (!this.isLoggedIn || !this.token) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          showCancel: false,
          success: () => {
            uni.navigateTo({
              url: '/pages/login/index'
            })
          }
        })
        return false
      }
      return true
    },

    /**
     * 上传头像
     * @param {String} filePath 文件路径
     */
    async uploadAvatar(filePath) {
      try {
        const response = await uploadApi.uploadAvatar(filePath)
        const { url } = response.data
        
        // 更新用户头像
        await this.updateUserInfo({ avatar: url })
        
        return response
      } catch (error) {
        console.error('上传头像失败:', error)
        throw error
      }
    }
  },

  // 持久化配置
  persist: {
    key: 'user-store',
    paths: ['userInfo', 'token', 'isLoggedIn', 'settings']
  }
})